package top.cardone.security.shiro.func;

import lombok.Setter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import top.cardone.core.util.func.Func1;

import java.util.Map;
import java.util.Objects;

/**
 * Created by cardone-home-001 on 2016/4/19.
 */
public class AuthorityFunc implements Func1<Boolean, Map<String, Object>> {
	@Setter
	String superPrincipal = "admin";

	@Setter
	String superRolepal = "admin";

	@Setter
	private String permittedsKeyName = "codes";

	@Setter
	private String permittedKeyName = "code";

	@Setter
	private String rolesKeyName = "roleCodes";

	@Setter
	private String roleKeyName = "roleCode";

	@Override
	public Boolean func(Map<String, Object> params) {
		if (Objects.equals(superPrincipal, SecurityUtils.getSubject().getPrincipal())) {
			return true;
		}

		if (SecurityUtils.getSubject().hasRole(superRolepal)) {
			return true;
		}

		String roles = MapUtils.getString(params, rolesKeyName);

		if (StringUtils.isNotBlank(roles)) {
			String[] roleArray = StringUtils.split(roles, ",");

			for (String role : roleArray) {
				if (SecurityUtils.getSubject().hasRole(role)) {
					return true;
				}
			}
		}

		String role = MapUtils.getString(params, roleKeyName);

		if (StringUtils.isNotBlank(role)) {
			if (SecurityUtils.getSubject().hasRole(role)) {
				return true;
			}
		}

		String permitteds = MapUtils.getString(params, permittedsKeyName);

		if (StringUtils.isNotBlank(permitteds)) {
			String[] permittedArray = StringUtils.split(permitteds, ",");

			for (String permitted : permittedArray) {
				if (SecurityUtils.getSubject().isPermitted(permitted)) {
					return true;
				}
			}
		}

		String permitted = MapUtils.getString(params, permittedKeyName);

		if (StringUtils.isNotBlank(permitted)) {
			return SecurityUtils.getSubject().isPermitted(permitted);
		}

		return false;
	}
}